import React, { useState } from 'react';
import { StyleSheet, TouchableOpacity, KeyboardAvoidingView, Platform, ScrollView, ViewStyle, TextStyle } from 'react-native';
import { useRouter } from 'expo-router';
import { MaterialIcons } from '@expo/vector-icons';
import { ThemedView } from '../../components/ThemedView';
import { ThemedText } from '../../components/ThemedText';
import { ThemedInput } from '../../components/ThemedInput';
import Toast from '../../components/Toast';
import { useTheme } from '../../components/theme/ThemeContext';
import { useAuth } from '../../store/auth/AuthContext';

interface FormData {
  email: string;
  password: string;
}

interface ToastState {
  visible: boolean;
  message: string;
  type: 'success' | 'error' | 'info';
}

export default function LoginScreen() {
  const router = useRouter();
  const { theme } = useTheme();
  const { login } = useAuth();
  const [formData, setFormData] = useState<FormData>({
    email: '',
    password: '',
  });
  const [isLoading, setIsLoading] = useState(false);
  const [toast, setToast] = useState<ToastState>({
    visible: false,
    message: '',
    type: 'info',
  });

  const showToast = (message: string, type: 'success' | 'error' | 'info' = 'info') => {
    setToast({
      visible: true,
      message,
      type,
    });
  };

  const hideToast = () => {
    setToast(prev => ({ ...prev, visible: false }));
  };

  const handleLogin = async () => {
    try {
      if (!formData.email || !formData.password) {
        showToast('请填写邮箱和密码', 'error');
        return;
      }

      setIsLoading(true);
      const result = await login(formData.email, formData.password);
      
      if (result.success) {
        console.log('Login successful');
        showToast('登录成功', 'success');
        await new Promise(resolve => setTimeout(resolve, 2000));
        router.replace('/(tabs)');
      } else {
        console.log('Login error:', result.message);
        showToast(result.message || '用户名或密码错误', 'error');
      }
    } catch (error: any) {
      console.error('Login exception:', error);
      const errorMessage = error.data?.message || error.message || '登录失败，请重试';
      showToast(errorMessage, 'error');
    } finally {
      setIsLoading(false);
    }
  };

  const getInputContainerStyle = (): ViewStyle => ({
    ...styles.inputContainer,
    borderColor: theme.colors.border,
  });

  const getLoginButtonStyle = (): ViewStyle => ({
    ...styles.loginButton,
    backgroundColor: isLoading ? theme.colors.border : theme.colors.primary,
  });

  const getFooterTextStyle = (): TextStyle => ({
    ...styles.footerText,
    color: theme.colors.primary,
  });

  return (
    <ThemedView style={styles.container}>
      {toast.visible && (
        <Toast
          message={toast.message}
          type={toast.type}
          onHide={hideToast}
        />
      )}
      
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardAvoid}
      >
        <ScrollView
          contentContainerStyle={styles.scrollContent}
          keyboardShouldPersistTaps="handled"
        >
          <ThemedView style={styles.header}>
            <ThemedText variant="h1" style={styles.title}>
              欢迎回来
            </ThemedText>
            <ThemedText variant="body" style={styles.subtitle}>
              登录您的AI创作档案馆账号
            </ThemedText>
          </ThemedView>

          <ThemedView style={styles.form}>
            <ThemedView style={getInputContainerStyle()}>
              <MaterialIcons
                name="email"
                size={24}
                color={theme.colors.primary}
              />
              <ThemedInput
                style={styles.input}
                placeholder="邮箱地址"
                keyboardType="email-address"
                autoCapitalize="none"
                value={formData.email}
                onChangeText={(text) => setFormData({ ...formData, email: text })}
              />
            </ThemedView>

            <ThemedView style={getInputContainerStyle()}>
              <MaterialIcons
                name="lock"
                size={24}
                color={theme.colors.primary}
              />
              <ThemedInput
                style={styles.input}
                placeholder="密码"
                secureTextEntry
                value={formData.password}
                onChangeText={(text) => setFormData({ ...formData, password: text })}
              />
            </ThemedView>

            <TouchableOpacity
              style={getLoginButtonStyle()}
              onPress={handleLogin}
              disabled={isLoading}
            >
              <ThemedText variant="body" style={styles.loginButtonText}>
                {isLoading ? '登录中...' : '登录'}
              </ThemedText>
            </TouchableOpacity>
          </ThemedView>

          <ThemedView style={styles.footer}>
            <TouchableOpacity
              onPress={() => router.push('/user/register')}
              style={styles.footerButton}
            >
              <ThemedText variant="body" style={getFooterTextStyle()}>
                还没有账号？立即注册
              </ThemedText>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => router.push('/')}
              style={styles.footerButton}
            >
              <ThemedText variant="body" style={getFooterTextStyle()}>
                忘记密码？
              </ThemedText>
            </TouchableOpacity>
          </ThemedView>
        </ScrollView>
      </KeyboardAvoidingView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  keyboardAvoid: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    padding: 24,
    justifyContent: 'center',
  },
  header: {
    marginBottom: 48,
  },
  title: {
    fontSize: 32,
    marginBottom: 12,
    textAlign: 'center',
    fontWeight: 'bold',
  },
  subtitle: {
    fontSize: 16,
    textAlign: 'center',
    opacity: 0.7,
    lineHeight: 22,
  },
  form: {
    gap: 16,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    borderWidth: 1,
    borderRadius: 12,
    padding: 14,
  },
  input: {
    flex: 1,
    marginLeft: 12,
    fontSize: 16,
  },
  loginButton: {
    borderRadius: 12,
    padding: 16,
    marginTop: 24,
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.2,
    shadowRadius: 4,
    elevation: 3,
  },
  loginButtonText: {
    color: '#FFFFFF',
    textAlign: 'center',
    fontSize: 16,
    fontWeight: '600',
  },
  footer: {
    marginTop: 40,
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingVertical: 20,
  },
  footerButton: {
    padding: 8,
  },
  footerText: {
    fontSize: 14,
    textDecorationLine: 'underline',
    opacity: 0.8,
  },
}); 